#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This"s Home Views
# -- 
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2018年3月1日 13:22:37
# ----------------------------------------------------------
from datetime import datetime
from flask import render_template, g, flash, redirect, url_for
from flask_login import login_required
from core.constant.sys_enum import SysEnum
from core.forms.post_forms import PostForm
from core.app import app, db
from core.models.post_model import Post


@app.route("/home", methods=["GET", "POST"])
@app.route("/index", methods=["GET", "POST"])
@app.route("/index/<int:page>", methods=["GET", "POST"])
@login_required
def index(page=1):
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, timestamp=datetime.utcnow(), author=g.user)
        db.session.add(post)
        db.session.commit()
        flash("Your post is now live!")
        return redirect(url_for("index"))
    # 分页显示
    posts = g.user.followed_posts().paginate(page, SysEnum.POSTS_PER_PAGE.value, False)
    return render_template("index.html", title="Home", form=form, posts=posts)


@app.route("/search", methods=["POST"])
@login_required
def search():
    if not g.search_form.validate_on_submit():
        return redirect(url_for("index"))
    return redirect(url_for("search_results", query=g.search_form.search.data))


@app.route("/search_results/<query>")
@login_required
def search_results(query):
    results = Post.query.whoosh_search(query, SysEnum.MAX_SEARCH_RESULTS.value).all()
    return render_template("search_results.html", query=query, results=results)
